<template>
  <ul class="comment-list">
    <li class="comment-list-item"  v-for="(item, i) in dataList" :key="item.id"
        :class="{'not-last': i < dataList.length - 1}">
      <el-avatar :size="42" :src="item.avatarUrl">
        <img src="../assets/img/default-avatar.png" />
      </el-avatar>
      <div class="classroom-list-item-content">
        <div class="box">
          <div class="classroom-list-item-content-wrap">
            <div class="comment-row">
              <label>{{ item.createUserName }}：</label>
              <p>{{ item.info }}</p>
            </div>
            <div class="comment-control">
              <span class="comment-control-time"><i class="classroom-time-icon"></i><span>{{ item.createTime }}</span></span>
              <span class="comment-control-like" :class="{'is-active': item.isLike}" @click="likeComment(item)">
                <i class="classroom-like-icon"></i><span>{{ item.likeNum }}</span>
              </span>
              <span class="comment-control-reply" @click="replay(item, '1')">
                <i class="classroom-comment-icon"></i><span>回复</span>
              </span>
              <span class="comment-control-del" @click="removeComment(item, '1')" v-permission="['VIDEO_STUDY_DEL_BUTTON']"
                    v-if="isMe(item.createUser)">
                <i class="classroom-del-icon"></i><span>删除</span>
              </span>
            </div>
          </div>
          <el-button type="danger" v-permission="['VIDEO_STUDY_MUTED_BUTTON']" @click="shutup(item)">禁言</el-button>
        </div>
        <ul v-if="item.showChildComment">
          <li class="comment-list-item comment-childlist-item" v-for="child in item.children" :key="child.id">
            <el-avatar :size="24" :src="child.avatarUrl">
              <img src="../assets/img/default-avatar.png" />
            </el-avatar>
            <div class="box">
              <div class="classroom-list-item-content-wrap">
                <div class="comment-row">
                  <label v-if="child.leaveWordId == child.pid">{{ child.createUserName }}：</label>
                  <label v-else>{{ child.createUserName }} <span>回复</span> {{ child.pcreateUserName }}：</label>
                  <p>{{ child.info }}</p>
                </div>
                <div class="comment-control">
                  <span class="comment-control-time"><i class="classroom-time-icon"></i><span>{{ child.createTime }}</span></span>
                  <span class="comment-control-like" :class="{'is-active': child.isLike}" @click="likeComment(child)">
                    <i class="classroom-like-icon"></i><span>{{ child.likeNum }}</span>
                  </span>
                  <span class="comment-control-reply" @click="replay(item, '2', child)">
                    <i class="classroom-comment-icon"></i><span>回复</span>
                  </span>
                  <span class="comment-control-del" @click="removeComment(child, '2', item)" v-permission="['VIDEO_STUDY_DEL_BUTTON']"
                        v-if="isMe(child.createUser)">
                    <i class="classroom-del-icon"></i><span>删除</span>
                  </span>
                </div>
              </div>
              <el-button type="danger" v-permission="['VIDEO_STUDY_MUTED_BUTTON']" @click="shutup(child)">禁言</el-button>
            </div>
          </li>
        </ul>
        <div class="show-child-comment-btn" v-if="item.showChildCommentBtn" @click="openChildComment(item)">
          <i class="el-icon-loading" v-if="item.loading"></i>
          共{{ item.pcount }}条回复, 点击查看
        </div>
        <el-pagination
          v-else-if="item.pcount > 10"
          @current-change="handleCurrentChange($event, item)"
          :current-page.sync="item.current"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="item.pcount">
        </el-pagination>
        <div class="classroom-comment-input" v-if="item.showInput">
          <el-avatar :size="42" :src="item.avatarUrl">
            <img src="../assets/img/default-avatar.png" />
          </el-avatar>
          <div class="classroom-comment-content">
            <el-input ref="ipt" v-model.trim="form.info" maxlength="200"
                      :placeholder="`回复 ${form.replayName}`" type="textarea" :autosize="{ minRows: 1, maxRows: 3}"></el-input>
            <el-button type="primary" @click="sendComment" :loading="sendLoading">发布</el-button>
          </div>
        </div>
      </div>
    </li>
  </ul>
</template>

<script>
import { add, getPage, addLike, delLike, del, qryLikeLeaveWordId, addShutup } from '@/api/onlineClass/comment'
import { cloud } from '@/framework/utils/request'
import { zeroFill } from '@/utils/index.js'
import { mapGetters } from 'vuex'

export default {
  name: 'CommentList',
  props: {
    videoId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dataList: [],
      form: {
        replayName: '',
        pid: '',
        leaveWordId: '',
        videoId: '',
        info: ''
      },
      sendLoading: false,
      replayCommentData: null,
      commentLikeList: []
    }
  },
  computed: {
    ...mapGetters(['authorities'])
  },
  mounted() {
    this.getMyLikeCommentId()
  },
  methods: {
    shutup(row) {
      addShutup({ userId: row.createUser }).then((res) => {
        if (res.code == '00000') {
          this.$message({
            message: '禁言成功',
            type: res.success ? 'success' : 'warning'
          })
        }
      })
    },
    sendComment() {
      if (this.form.info) {
        this.sendLoading = true
        add(this.form).then((res) => {
          this.form.info = ''
          this.replayCommentData.pcount++
          this.openChildComment(this.replayCommentData)
        }).finally(() => {
          this.sendLoading = false
        })
      } else {
        this.$message.warning('不能发送空内容!')
      }
    },
    replay(row, type, child) { // row: 评论行数据; type: 1 代表评论列表 2 代表子评论列表; child 子评论行数据
      this.replayCommentData = row
      this.dataList.forEach((item) => { item.showInput = false })
      if (type == '1') {
        this.form.replayName = row.createUserName
        this.form.pid = row.id
        this.form.leaveWordId = row.id
        this.form.videoId = this.videoId
      } else { // 回复子评论
        this.form.replayName = child.createUserName
        this.form.pid = child.id
        this.form.leaveWordId = row.id
        this.form.videoId = this.videoId
        this.form.replayName = child.createUserName
      }
      row.showInput = true
      this.$nextTick(() => {
        this.$refs.ipt[0].focus()
      })
    },
    removeComment(row, type, pRow) {
      del({
        id: row.id,
        ids: [
          row.id
        ]
      }).then((res) => {
        this.$message({
          message: res.success ? '删除成功' : res.message,
          type: res.success ? 'success' : 'warning'
        })
        if (type == '1') {
          this.$emit('refresh')
        } else {
          this.openChildComment(pRow)
        }
      })
    },
    handleCurrentChange(val, row) {
      this.openChildComment(row, val)
    },
    getData(arr) { // 获取评论列表
      this.dataList = this.formatData(arr)
      this.$emit('moreCallback', this.dataList.length)
    },
    openChildComment(row, current) { // 获取子评论列表
      row.loading = true
      getPage({
        videoId: this.videoId,
        leaveWordId: row.id,
        pageNo: current
      }).then((res) => {
        row.pcount = res.data.totalRows
        row.children = res.data.rows.map((item) => {
          item.createTime = this.formatDate(item.createTime)
          item.avatarUrl = `${location.origin}${process.env.VUE_APP_BASE_API}${cloud.file}/sysFileInfo/public/preview?fileId=${item.createUserAvatar}`
          item.likeNum = item.likeNum > 0 ? item.likeNum : 0
          item.current = 1
          item.isLike = this.commentLikeList.includes(item.id)
          return item
        })
        row.showChildComment = row.children.length > 0
        row.showChildCommentBtn = row.pcount > 0 && !row.children.length
      }).finally(() => {
        row.loading = false
      })
    },
    likeComment(row) {
      if (!row.isLike) {
        addLike(row.id).then((res) => {
          if (!isNaN(+row.likeNum)) {
            if (row.isLike) {
              row.likeNum = (row.likeNum * 1 - 1).toString()
            } else {
              row.likeNum = (row.likeNum * 1 + 1).toString()
            }
          }
        })
      } else {
        delLike({ id: row.id, leaveWordId: row.leaveWordId || row.id }).then((res) => {
          if (!isNaN(+row.likeNum)) {
            if (row.isLike) {
              row.likeNum = (row.likeNum * 1 - 1).toString()
            } else {
              row.likeNum = (row.likeNum * 1 + 1).toString()
            }
          }
        })
      }
      row.isLike = !row.isLike
    },
    more(arr) {
      const res = this.formatData(arr)
      this.dataList = this.dataList.concat(res)
      this.$emit('moreCallback', this.dataList.length)
    },
    getMyLikeCommentId() {
      qryLikeLeaveWordId().then((res) => {
        this.commentLikeList = res.data
        this.dataList.forEach((item) => { // 为顶层评论点赞添加状态
          item.isLike = this.commentLikeList.includes(item.id)
        })
      })
    },
    formatDate(dateStr) {
      if (!isNaN(Date.parse(dateStr))) {
        const dates = new Date(dateStr)
        const yyyy = dates.getFullYear()
        const MM = zeroFill(dates.getMonth() + 1)
        const dd = zeroFill(dates.getDate())
        const HH = zeroFill(dates.getHours())
        const mm = zeroFill(dates.getMinutes())
        return `${yyyy}-${MM}-${dd} ${HH}:${mm}`
      }
      return ''
    },
    isMe(id) {
      if (this.authorities.includes('VIDEO_STUDY_DEL_BUTTON')) { // 判断有无管理员权限管理员
        return true
      }
      return this.$store.state.user.userId === id
    },
    formatData(arr) {
      return arr.map((item) => {
        item.pcount = item.pcount ? item.pcount : 0
        item.showChildComment = item.children.length > 0
        item.showChildCommentBtn = item.pcount > 0 && !item.children.length
        item.current = 1
        item.showInput = false
        item.loading = false
        item.isLike = this.commentLikeList.includes(item.id)
        return item
      })
    }
  }
}
</script>

<style lang="scss" scoped>
ul {
  margin-block-start: 0;
  margin-block-end: 0;
  padding-inline-start: 0;
  li {
    list-style: none;
  }
}
.comment-list {
  font-family: "Source Han Sans CN";
  &-item {
    display: flex;
    align-items: flex-start;
    padding: 20px 0;
    .classroom-list-item-content {
      position: relative;
      width: 100%;
      height: 100%;
      .box {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      // margin-bottom: 20px;
      &-wrap {
        width: 83%;
        .comment-row {
          display: flex;
          align-items: flex-start;
          margin-bottom: 13px;
          label {
            font-weight: 400;
            font-size: 14px;
            color: #004fff;
            white-space: nowrap;
            span {
              color: #0a0a0a;
            }
          }
          p {
            font-weight: 400;
            font-size: 14px;
            text-align: left;
            color: #0a0a0a;
            margin-block-start: 0;
            margin-block-end: 0;
          }
        }
        .comment-control {
          width: 100%;
          i {
            display: inline-block;
            width: 14px;
            height: 14px;
            vertical-align: middle;
            margin-right: 2px;
          }
          &-time {
            font-weight: 500;
            font-size: 14px;
            color: #808080;
            span {
              vertical-align: middle;
            }
          }
          &-like {
            font-weight: 500;
            font-size: 14px;
            color: #808080;
            margin-left: 58px;
            cursor: pointer;
            span {
              vertical-align: middle;
            }
          }
          .is-active {
            color: #ff7b3f;
            .classroom-like-icon {
              background: url("../assets/icons/like-active-icon.png") no-repeat;
              background-size: cover;
            }
          }
          &-reply {
            font-weight: 500;
            font-size: 14px;
            color: #004fff;
            margin-left: 12px;
            cursor: pointer;
            span {
              vertical-align: middle;
            }
          }
          &-del {
            font-weight: 500;
            font-size: 14px;
            color: #fa4b4b;
            margin-left: 12px;
            cursor: pointer;
            span {
              vertical-align: middle;
            }
          }
        }
      }
      .comment-childlist-item {
        padding: 12px 0 0;
        .el-avatar {
          width: 24px;
          margin-right: 12px;
          // margin-bottom: 20px;
          flex: none;
        }
        .box {
          width: 100%;
        }
      }
    }
  }
  .el-avatar {
    width: 42px;
    margin-right: 12px;
    // margin-bottom: 20px;
    flex: none;
  }
  .not-last {
    .classroom-list-item-content::after {
      content: "";
      position: absolute;
      bottom: -20px;
      left: 0;
      right: 0;
      bottom: 0;
      transform: translateY(100%);
      height: 20px;
      border-bottom: 1px dashed #707070;
      width: 100%;
    }
  }
}
.classroom-time-icon {
  background: url("../assets/icons/time-icon.png") no-repeat;
  background-size: cover;
}
.classroom-like-icon {
  background: url("../assets/icons/like-icon.png") no-repeat;
  background-size: cover;
}
.classroom-del-icon {
  background: url("../assets/icons/del-icon.png") no-repeat;
  background-size: cover;
}
.classroom-comment-icon {
  background: url("../assets/icons/comment-icon.png") no-repeat;
  background-size: cover;
}
.show-child-comment-btn {
  font-size: 14px;
  color: #9499A0;
  cursor: pointer;
  padding-top: 8px;
}
::v-deep .el-pagination {
  padding-left: 0px;
}
.classroom-comment-input {
  position: relative;
  display: flex;
  align-items: center;
  margin: 12px 0 10px;
  .el-avatar {
    width: 42px;
    margin-right: 12px;
    flex: none;
  }
  .el-textarea {
    width: 83%;
    ::v-deep textarea {
      background: #f1f2f3;
      min-height: 43px !important;
    }
  }
  ::v-deep .el-textarea__inner:focus {
    border-color: #f1f2f3;
  }
}
.classroom-comment-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
